import { defineStore } from 'pinia';
import axios from '@/plugins/axios';
import { ElMessage } from 'element-plus';

export interface Resource {
  id: number;
  title: string;
  category: 'DOCUMENT' | 'VIDEO' | 'AUDIO' | 'IMAGE';
  fileType: string;
  fileSize: number;
  fileUri: string;
  uploadTime: string;
}

export interface ResourceCreateRequest {
  title: string;
  category: 'DOCUMENT' | 'VIDEO' | 'AUDIO' | 'IMAGE';
  file: File;
}

export interface ResourceUpdateRequest {
  id: number;
  title: string;
  category: 'DOCUMENT' | 'VIDEO' | 'AUDIO' | 'IMAGE';
  file?: File;
}

export const useResourceStore = defineStore('resource', {
  state: () => ({
    resources: [] as Resource[],
  }),

  actions: {
    async fetchResources() {
      try {
        const response = await axios.get('/api/resource');
        if (response.data.code === 200) {
          this.resources = response.data.data;
          return this.resources;
        }
        throw new Error(response.data.message || '获取资源列表失败');
      } catch (error: any) {
        ElMessage.error(error.message || '获取资源列表失败');
        throw error;
      }
    },

    async fetchResourcesByCategory(category: string) {
      try {
        const response = await axios.get(`/api/resource/category/${category}`);
        if (response.data.code === 200) {
          return response.data.data;
        }
        throw new Error(response.data.message || '获取资源列表失败');
      } catch (error: any) {
        ElMessage.error(error.message || '获取资源列表失败');
        throw error;
      }
    },

    async fetchResourceById(id: number) {
      try {
        const response = await axios.get(`/api/resource/${id}`);
        if (response.data.code === 200) {
          return response.data.data;
        }
        throw new Error(response.data.message || '获取资源详情失败');
      } catch (error: any) {
        ElMessage.error(error.message || '获取资源详情失败');
        throw error;
      }
    },

    async createResource(data: ResourceCreateRequest) {
      try {
        if (!data.file || !(data.file instanceof File)) {
          throw new Error('请选择有效文件');
        }
        const formData = new FormData();
        formData.append('title', data.title);
        formData.append('category', data.category);
        formData.append('file', data.file);
        const response = await axios.post('/api/resource', formData, {
          headers: { 'Content-Type': 'multipart/form-data' },
        });
        if (response.data.code === 200) {
          this.resources.push(response.data.data);
          ElMessage.success('创建资源成功');
          return response.data.data;
        }
        throw new Error(response.data.message || '创建资源失败');
      } catch (error: any) {
        ElMessage.error(error.message || '创建资源失败');
        throw error;
      }
    },

    async updateResource(data: ResourceUpdateRequest) {
      try {
        const formData = new FormData();
        formData.append('id', data.id.toString());
        formData.append('title', data.title);
        formData.append('category', data.category);
        if (data.file) {
          if (!(data.file instanceof File)) {
            throw new Error('无效的文件');
          }
          formData.append('file', data.file);
        }
        const response = await axios.put('/api/resource', formData, {
          headers: { 'Content-Type': 'multipart/form-data' },
        });
        if (response.data.code === 200) {
          const index = this.resources.findIndex(r => r.id === data.id);
          if (index !== -1) {
            this.resources[index] = response.data.data;
          }
          ElMessage.success('更新资源成功');
          return response.data.data;
        }
        throw new Error(response.data.message || '更新资源失败');
      } catch (error: any) {
        ElMessage.error(error.message || '更新资源失败');
        throw error;
      }
    },

    async deleteResource(id: number) {
      try {
        const response = await axios.delete(`/api/resource/${id}`);
        if (response.data.code === 200) {
          this.resources = this.resources.filter(r => r.id !== id);
          ElMessage.success('删除资源成功');
          return response.data.data;
        }
        throw new Error(response.data.message || '删除资源失败');
      } catch (error: any) {
        ElMessage.error(error.message || '删除资源失败');
        throw error;
      }
    },
  },
});